﻿using FaceBook;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace com.baidu.ai
{
    public class FaceAdd
    {
        // 人脸注册
        public static string add(IFormFile file)
        {
            string token = AccessToken.getAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            Stream fs = file.OpenReadStream();
            var img = FaceAdd.FileToBase64(fs);

            // str 中json仔细阅读上面的Body中放置请求参数
            String str = "{\"image\":\"" + img + "\",\"image_type\":\"FACE_TOKEN\",\"group_id\":\"group_repeat\",\"user_id\":\"user1\",\"user_info\":\"abc\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            //Console.WriteLine("人脸注册:");
            //Console.WriteLine(result);
            return result;
        }

        /// <summary>
        ///  文件转换成Base64字符串
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns></returns>
        public static String FileToBase64(Stream fs)
        {
            string strRet = null;

            try
            {
                if (fs == null) return null;
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, bt.Length);
                strRet = Convert.ToBase64String(bt);
                fs.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return strRet;
        }
    }
}